#!/bin/bash

function syscfg_before_install()
{
	if [ "$LOGNAME" != "root" ]; then
		read -n 1 -p "Need root user previlege(sudo su), quit!"
		return 1
	fi

	for cfg in $@; do
		if [ -f "/tmp/.ubuntu-cfg-for-building" ]; then
			grep $cfg /tmp/.ubuntu-cfg-for-building > /dev/null && (
				read -n 1 -p "$cfg has been installed";
				return 1
			)
		fi
		if [ ! -d "$cfg"_cfg ]; then
			read -n 1 -p "The specified configuration $cfg is invalid, quit!"
			return 1
		fi
		for file in "$cfg"_cfg/*.a; do
			target=$(head -n 1 $file)
			if [ ! -f "$target" ]; then
				read -n 1 -p "File $file is invalid, quit!"
				return 1
			fi
		done
	done

	for cfg in $@; do
		for file in "$cfg"_cfg/*.a; do
			target=$(head -n 1 $file)
			tail -n +2 $file >> $target
		done
	done

	echo $@ > ./install.log
	echo $@ > /tmp/.ubuntu-cfg-for-building

	return 0
}

function tools_install()
{
	sudo apt-get -y update
	sudo apt-get -y upgrade
	#sudo sed -i 's/eth0/eth1/' /etc/udev/rules.d/70-persistent-net.rules
	for cfg in $@; do
		if [ -f "$cfg"_cfg/installtool ]; then
			source "$cfg"_cfg/installtool
		fi
	done

	return 0
}

function syscfg_after_install()
{
	sudo dpkg-reconfigure dash
	sudo ntpdate ntp.hp.net
	sudo hwclock --systohc

	return 0
} 


pushd $(dirname $0) > /dev/null

if [ ! -f ./install.log ]; then
	if syscfg_before_install common $@; then
		read -n 1 -p "Please run this script again with no any parameters to continue installing after rebooting."
		reboot
	fi
	exit 0
else
	last_paras=$(head -n 1 ./install.log)
	tools_install common $last_paras
	syscfg_after_install

	read -n 1 -p "Finished! Will reboot."
	rm -f install.log
	sudo reboot
fi

popd > /dev/null
